const dataHandler = (data, type) => {
  if (type === 'tree') {
    const list = []
    data.forEach(item => {
      if (item.deleted !== undefined) {
        item.deleted = !!item.deleted
      }
      if (item.level === '0' || item.level === 0) {
        item.children = []
        if (item.deleted === undefined) {
          delete(item.level)
        }
        list.push(item)
      }
    })
    for (const father of list) {
      for (const son of data) {
        if (father.id === son.pid && (son.level === '1' || son.level === 1)) {
          son.children = []
          if (son.deleted === undefined) {
            delete(son.level)
          }
          father.children.push(son)
        }
      }
    }
    {}
    for (const grandfather of list) {
      for (const father of grandfather.children) {
        for (const son of data) {
          if (son.pid === father.id && (son.level === '2'|| son.level === 2)) {
            son.pid = grandfather.id + ',' + father.id
            if (son.deleted === undefined) {
              delete(son.level)
            }
            father.children.push(son)
          }
        }
      }
    }
    return list
    } else {
      return data
    }
    
  }

module.exports = {
  dataHandler
}
